
import sublime
import sublime_plugin

import getpass
import time
import re

# 插入文件头部信息
class wlgame_insert_lua_headerCommand(sublime_plugin.TextCommand):

	def getHeaderComment (self):
		comment = "";
		comment = comment + "-- ================================================================\n"
		comment = comment + "-- 文件名: $TM_FILENAME\n"
		comment = comment + "-- 描述: ${1:功能描述}\n"
		comment = comment + "-- 版权: Copyright © 2016-2018 华泰信合(深圳)网络科技有限公司 版权所有\n"
		comment = comment + "-- 作者: ${2:%s}\n"
		comment = comment + "-- 创建日期: %s\n"
		comment = comment + "-- 更新日期: %s\n"
		comment = comment + "-- 备注: \n"
		comment = comment + "-- ================================================================\n"
		comment = comment + "--"

		strTime = time.strftime('%Y-%m-%d',time.localtime(time.time()));
		comment = comment % (getpass.getuser(), strTime, strTime)
		return comment


	def run(self, edit):

		view = self.view

		if not view.file_name().endswith(".lua"):
			return

		view.run_command("insert_snippet", 
			{
            	"contents": self.getHeaderComment()
        	}
        )  

# 插入函数注释
class wlgame_insert_lua_func_commentCommand(sublime_plugin.TextCommand):

	# 获取注释内容
	def getFuncComment (self, funcHeader):
		print("funcHeader", funcHeader)

		comment = ""
		comment = comment + '-- ${1:功能描述}\n'

		pattern = '\\([\\w+:,\\s.]+\\)'
		res = re.search(pattern, funcHeader)
		if res:
			strArgs = res.group()
			strArgs = strArgs.replace("(", "").replace(")", "").replace(" ", "")
			# print(strArgs)

			args = strArgs.split(",")
			# print(args)
			for i in range(len(args)):
				comment = comment + '-- @param %s ${%d: }\n' % (args[i], i+2)

		comment = comment + "-- @return \n"
		comment = comment + "--"
		
		return comment

	# 插入注释
	def insertFuncComment(self, edit, point, funcHeader, isWrap):
		content = self.getFuncComment(funcHeader)

		if isWrap:
			content = content + "\n"

		self.view.run_command("insert_snippet", 
			{
            	"contents": content,
            	"scope": "source.lua"
        	}
        )  

	def run(self, edit):

		view = self.view

		if not view.file_name().endswith(".lua"):
			return

		selection = view.sel()

		curLineRegion = selection[0]
		print(view.substr(curLineRegion))
		curLineRegion = view.line(curLineRegion.begin())

		curLineContent = view.substr(curLineRegion)
		if curLineContent.find("function") >= 0:
			# 当前行包含function关键字
			point = curLineRegion.begin()
			self.insertFuncComment(edit, point, curLineContent, True)
		else:
			# 判断下一行
			p1 = view.rowcol(curLineRegion.begin())
			point = view.text_point(p1[0]+1,p1[1])
			lineRegion = view.line(point)
			lineContent = view.substr(lineRegion)
			print(lineContent)
			if lineContent.find("function") >= 0:
				# 当前行包含函数开头
				self.insertFuncComment(edit, curLineRegion.begin(), lineContent, False)
